//
// Created by DELL on 2021/3/12.
//
#include "hook.h"
#include "iomanager.h"
#include "log.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <cstring>

sylar::Logger::ptr g_logger = SYLAR_LOG_ROOT();

void test_sleep() {
    sylar::IOManager ioManager(1, true, "hook");
    ioManager.schedule([]() {
        sleep(2);
        SYLAR_LOG_INFO(g_logger) << " sleep 2 ";
    });
    ioManager.schedule([]() {
        sleep(3);
        SYLAR_LOG_INFO(g_logger) << " sleep 3 ";
    });
    SYLAR_LOG_INFO(g_logger) << " test_sleep ";
}

void test_socket() {
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(80);
    inet_pton(AF_INET, "182.61.200.6", &addr.sin_addr.s_addr);

    SYLAR_LOG_INFO(g_logger) << " connection begin ";
    int rt = connect(sock, (const sockaddr *) &addr, sizeof(addr));
    SYLAR_LOG_INFO(g_logger) << "connect rt = " << rt << " errno = " << errno<< strerror(errno)
                             << "  " << strerror(errno);
    if (rt) {
        return;
    }

    const char data[] = "GET / HTTP/1.0\r\n\r\n";
    rt = send(sock, data, sizeof(data), 0);
    SYLAR_LOG_INFO(g_logger) << "send rt = " << rt << " error = " << errno << strerror(errno)
    <<"\n" << data;
    if (rt <= 0) {
        return;
    }

    std::string buff;
    buff.resize(4096);

    rt = recv(sock, &buff[0], buff.size(), 0);
    SYLAR_LOG_INFO(g_logger) << "recv rt = " << rt << " error = " << errno<< strerror(errno)
                             << "\n" << buff;
    if (rt <= 0) {
        return;
    }
}

int main(int argc, char **argv) {
//    test_sleep();
    sylar::IOManager iom;
    iom.schedule(test_socket);
    return 0;
}
